package com.zlx.guguanjia.controller;

import com.baomidou.kaptcha.Kaptcha;
import com.zlx.guguanjia.entity.Result;
import com.zlx.guguanjia.entity.SysResource;
import com.zlx.guguanjia.entity.SysUser;
import com.zlx.guguanjia.service.SysResourceService;
import com.zlx.guguanjia.service.SysUserService;
import com.zlx.guguanjia.util.EncryptUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 周罗校
 * @Description
 * @ClassName MainController
 * @date 2020.11.03 13:08:18
 * 该版权归周罗校所有，最终解释权以官方为准
 */
@CrossOrigin
@RestController
@RequestMapping("/main/")
public class MainController {
    @Autowired
    private SysUserService service;
    @Autowired
    private Kaptcha kaptcha;
    @Autowired
    private SysResourceService sysResourceService;

    @GetMapping("login")
    public Result login(String username,String password,String code,HttpSession session){
        String message = null;
        if (kaptcha.validate(code)){
            //验证码正确
            SysUser loginUser = new SysUser();
            loginUser.setUsername(username);
            //密码加密+用户名作为盐值
            loginUser.setPassword(EncryptUtils.MD5_HEX(EncryptUtils.MD5_HEX(password)+username));
            Map<String,Object> map = new HashMap<>();
            loginUser=service.selectOne(loginUser);
            if (loginUser!=null){
                session.setAttribute("loginUser",loginUser);
                //设置登陆时间
                SysUser user = new SysUser();
                user.setLoginDate(new Date());
                user.setId(loginUser.getId());
                //更新登录时间
                service.updateByPrimaryKeySelective(user);
                //清空密码
                loginUser.setPassword(null);
                //根据用户id动态获取菜单
                List<SysResource> resources = sysResourceService.selctByUid(loginUser.getId());
                //用于鉴权
                session.setAttribute("resources",resources);
                map.put("loginUser",loginUser);
                map.put("resources",resources);
                return new Result(map);
            }else {
                message = "用户名或密码错误";
            }
        }else {
            message="验证码错误";
        }
        return new Result(false,message,null);
    }
    @GetMapping("exitLogging")
    public Result exitLogging(HttpSession session){
        //清空session
        session.removeAttribute("loginUser");
        return new Result(true,"退出成功",null);
    }

    @GetMapping("getMenuByUid/{uid}")
    public Result getMenuByUid(@PathVariable("uid") Long uid){
        return new Result(sysResourceService.selectResourceByRid(uid));
    }
}
